package com.kye.express.business.personal_my_bill.monthly_balance_bill.detail;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Menu;
import android.view.MenuItem;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.support.v7.widget.RxToolbar;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.personal_my_bill.Bill.list.BillListActivity;
import com.kye.express.databinding.ActivityMonthlyBalanceBillBinding;
import com.kye.express.utils.PhoneUtils;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.bill.MonthlyBalanceBillBean;

import io.reactivex.functions.Consumer;

public class MonthlyBalanceBillDetailActivity extends BaseAppCompatActivity implements MonthlyBalanceBillDetailContract.MonthlyBalanceBillDetailView {

    private static final String KEY_MONTHLY_BALANCE_BILL = "KEY_MONTHLY_BALANCE_BILL";

    private MonthlyBalanceBillDetailContract.MonthlyBalanceBillDetailPresenter mPresenter;
    private ActivityMonthlyBalanceBillBinding mBinding;
    private MonthlyBalanceBillBean mMonthlyBalanceBillBean;
    private Dialog mProgressDialog;

    private MaterialDialog mDialog;
    private MaterialDialog mConfirmedDialog;

    public static void startActivityForResult(Activity activity, MonthlyBalanceBillBean bean, int requestCode) {
        activity.startActivityForResult(
                new Intent(activity, MonthlyBalanceBillDetailActivity.class)
                        .putExtra(KEY_MONTHLY_BALANCE_BILL, bean),
                requestCode
        );
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_monthly_balance_bill);

        initView();
        initEvent();
        initData();
    }

    private void initView() {
    }

    private void initEvent() {
        ToolbarManager.setToolbar(this, mBinding.toolbar);

        RxToolbar.itemClicks(mBinding.toolbar)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<MenuItem>() {
                    @Override
                    public void accept(MenuItem menuItem) throws Exception {
                        mPresenter.callToFinance();
                    }
                });

        RxView.clicks(mBinding.linearLayoutErrorNet.btErrorNetRetry)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mBinding.statusLayout.showLoadingView();
                    }
                });

        RxView.clicks(mBinding.linearLayoutErrorServer.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mBinding.statusLayout.showLoadingView();
                    }
                });

        RxView.clicks(mBinding.linearLayoutEmpty.btEmptyRetry)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mBinding.statusLayout.showLoadingView();
                    }
                });

        mBinding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                mPresenter.getMonthlyBalanceBill(mMonthlyBalanceBillBean);
            }
        });

        RxView.clicks(mBinding.buttonBillList)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        BillListActivity.startActivity(MonthlyBalanceBillDetailActivity.this, mBinding.getBean());
                    }
                });

        RxView.clicks(mBinding.buttonConfirm)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.confirmBill(mMonthlyBalanceBillBean);
                    }
                });
    }

    private void initData() {
        mPresenter = new MonthlyBalanceBillDetailContract.MonthlyBalanceBillDetailPresenter();
        mPresenter.bind(this);
        mMonthlyBalanceBillBean = (MonthlyBalanceBillBean) getIntent().getSerializableExtra(KEY_MONTHLY_BALANCE_BILL);

        mBinding.statusLayout.showLoadingView();

        setTitle(mMonthlyBalanceBillBean.getBillDate().split("-")[1] + "月账单");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_monthly_balance_bill_detail, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
        if (mProgressDialog != null && mProgressDialog.isShowing()) mProgressDialog.dismiss();
        if (mConfirmedDialog != null && mConfirmedDialog.isShowing()) mConfirmedDialog.dismiss();
    }

    @Override
    public void onError() {
        mBinding.statusLayout.showErrorNetworkView();
    }

    @Override
    public void onError(String msg) {
        mBinding.statusLayout.showErrorServerView();
        ToastManager.show(this, msg);
    }

    @Override
    public void onLoading() {
        mBinding.statusLayout.showLoadingView();
    }

    @Override
    public void onLoaded() {

    }

    @Override
    public void onLoadedData(MonthlyBalanceBillBean monthlyBalanceBillBean) {
        mMonthlyBalanceBillBean = monthlyBalanceBillBean;

        mBinding.statusLayout.showContentView();

        mBinding.setBean(monthlyBalanceBillBean);
    }

    @Override
    public void onActionLoading() {
        mProgressDialog = KyeProgressDialog.show(this, mProgressDialog);
    }

    @Override
    public void onCallToFinance(String financePhone) {
        if (mDialog == null) {
            mDialog = new MaterialDialog.Builder(MonthlyBalanceBillDetailActivity.this)
                    .title("温馨提示")
                    .content("是否拨打财务电话")
                    .positiveText("确认拨打")
                    .negativeText(R.string.common_cancel)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            PhoneUtils.call(MonthlyBalanceBillDetailActivity.this, financePhone);
                        }
                    })
                    .build();
        }
        mDialog.show();
    }

    @Override
    public void onActionError(String msg) {
        ToastManager.show(this, msg);
    }

    @Override
    public void onActionError() {
        ToastManager.show(this, R.string.common_net_error);
    }

    @Override
    public void onActionLoaded() {
        mProgressDialog.dismiss();
    }

    @Override
    public void onConfirmed() {
        if (mConfirmedDialog == null) {
            mConfirmedDialog = new MaterialDialog.Builder(MonthlyBalanceBillDetailActivity.this)
                    .title("账单已确认")
                    .content("账单确认成功，跨越专员正在开具发票并寄出，请耐心等待")
                    .positiveText("知道了")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            setResult(RESULT_OK);
                            finish();
                        }
                    })
                    .build();
        }
        mConfirmedDialog.show();
    }
}
